import java.io.IOException;
import java.net.*;
import java.util.Scanner;

//客户端
public class UdpEchoClient {
        DatagramSocket socket = null;

        public UdpEchoClient() throws SocketException {
            socket = new DatagramSocket();
        }

        public void stack() throws IOException {
            Scanner scanner = new Scanner(System.in);

            while(true) {
                //从控制台读取数据
                System.out.print(">:");
                String str = scanner.next();
                DatagramPacket packet = new DatagramPacket(str.getBytes(),str.getBytes().length
                        , InetAddress.getByName("127.0.0.1"),2000);

                //请求数据
                socket.send(packet);

                //获取响应数据
                DatagramPacket packet1 = new DatagramPacket(new byte[4096],4096);
                socket.receive(packet1);

                //打印请求响应信息;
                String str1 = new String(packet1.getData(),0,packet1.getLength());
                System.out.printf("[%d:%s] %s %s \n",packet1.getPort(),packet1.getAddress().toString(),str,str1);

            }
        }

    public static void main(String[] args) throws IOException {
        UdpEchoClient client = new UdpEchoClient();
        client.stack();
    }
}
